# -*- coding:utf-8 -*-
"""
@Created on : 2025/05/07 06:48 AM
@Author: linfeng
@Des: 工具函数
"""

import hashlib
import random
import uuid
from passlib.handlers.pbkdf2 import pbkdf2_sha256
from html.parser import HTMLParser
import threading
import json
import os

def random_str():
    """
    唯一随机字符串
    :return: str
    """
    only = hashlib.md5(str(uuid.uuid1()).encode(encoding='UTF-8')).hexdigest()
    return str(only)


def en_password(psw: str):
    """
    密码加密
    :param psw: 需要加密的密码
    :return: 加密后的密码
    """
    password = pbkdf2_sha256.hash(psw)
    return password


def check_password(password: str, old: str):
    """
    密码校验
    :param password: 用户输入的密码
    :param old: 数据库密码
    :return: Boolean
    """
    check = pbkdf2_sha256.verify(password, old)
    if check:
        return True
    else:
        return False


def code_number(ln: int):
    """
    随机数字
    :param ln: 长度
    :return: str
    """
    code = ""
    for i in range(ln):
        ch = chr(random.randrange(ord('0'), ord('9') + 1))
        code += ch

    return code


 
class MLStripper(HTMLParser):
    def __init__(self):
        super().__init__()
        self.reset()
        self.strict = False
        self.convert_charrefs= True
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)
 
def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

def get_sonid_all(data, id):
    """
    获取所有子ID
    :param data: 数据
    :param id: 父ID
    :return: list
    """
    sonid = []
    for i in data:
        if i['pid'] == id:
            sonid.append(i['id'])
            sonid.extend(get_sonid_all(data, i['id']))
    return sonid

def get_parentid_all(data, id):
    """
    获取所有父ID
    :param data: 数据
    :param id: 子ID
    :return: list
    """
    parentid = []
    for i in data:
        if i['id'] == id:
            parentid.append(i['pid'])
            parentid.extend(get_parentid_all(data, i['pid']))
    return parentid

def get_cate_info(id, field: str, default: str = ""):
    """
    获取栏目信息
    :param id: 栏目ID
    :param field: 字段
    :param default: 默认值
    """
    file_lock = threading.Lock()
    if not os.path.exists("data/category.json"):
        return []
    
    try:
        
        with file_lock:
            with open("data/category.json", "r", encoding="utf-8") as f:
                data = json.load(f)
                if data[str(id)]:
                    print(data[str(id)])
                    return data[str(id)][field] if data[str(id)][field] else default
                else:
                    return default
    except Exception as e:
        return []

#获取栏目父ID
def get_parent_id(id):
	return get_cate_info(id,'parent_id',0)

#获取栏目名称
def get_cate_name(id,val:str=''):
	return get_cate_info(id,'cate_name',val)

#获取某一分类的子类数量
def get_son_id_num(id):
	return get_cate_info(id,'child',0)

#查找某一分类的所有子类
def get_son_id_all(id):
    astr=''
    dt=id.split(',')
    for val in dt:
        astr = astr + ',' + get_cate_info(val,'son_id',val)
    return astr.strip(',')

#查找某一分类的所有父类
def get_tree_parent(id): 
	return get_cate_info(id,'parent',id)
